package com.xiaoshuidi.cloud.module.rooms.controller.admin.roomequipment;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.operatelog.core.annotations.OperateLog;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomequipment.vo.*;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomhouse.vo.HouseImportReq;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomhouse.vo.RoomHouseImportResult;
import com.xiaoshuidi.cloud.module.rooms.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.rooms.enums.EquipmentPositionType;
import com.xiaoshuidi.cloud.module.rooms.framework.utils.CodeUtil;
import com.xiaoshuidi.cloud.module.rooms.mq.listener.RoomEquipmentListener;
import com.xiaoshuidi.cloud.module.rooms.service.RoomEquipmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.success;
import static com.xiaoshuidi.cloud.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

/**
 * 资产管理-资产清单
 *
 * @author Link
 * @since 2023-05-18
 */
@Tag(name = "管理后台 - 房源资产")
@RestController
@RequestMapping(ApiConstants.NAME + "/equipment")
@RequiredArgsConstructor
public class RoomEquipmentController {

    @Resource
    private RoomEquipmentService roomEquipmentService;


    private final StringRedisTemplate stringRedisTemplate;

    private final CodeUtil codeUtil;

    /**
     * 创建房源资产
     **/
    @Operation(summary = "创建房源资产")
    @PostMapping("/create")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:create')")
    public CommonResult<Long> create(@RequestBody RoomEquipmentCreateReq req) {
        return success(roomEquipmentService.create(req));
    }

    /**
     * 房源资产状态变更
     **/
    @Operation(summary = "房源资产状态变更", description = "status:4是报废 5是遗失")
    @GetMapping("/updateStatus")
    @Parameters({
            @Parameter(name = "id", description = "物资id"),
            @Parameter(name = "status", description = "调配目的房间"),
    })
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:update-status')")
    public CommonResult<Boolean> updateStatus(@RequestParam("id") Long id, @RequestParam("status") String status) {
        roomEquipmentService.updateStatus(id, status);
        return success(true);
    }

    /**
     * 房源资产编辑
     **/
    @Operation(summary = "房源资产编辑")
    @PutMapping("/edit")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:edit')")
    public CommonResult<Boolean> edit(@RequestBody RoomEquipmentUpdateReqVO req) {
        return success(roomEquipmentService.edit(req));
    }

    /**
     * 房源资产批量调配
     **/
    @Operation(summary = "房源资产批量调配")
    @PutMapping("/updatedp")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:updatedp')")
    public CommonResult<Boolean> updatedp(@RequestBody RoomEquipmentUpDpReqVo req) {
        roomEquipmentService.updateBatchDp(req);
        return success(true);
    }

    /**
     * 批量上传房源资产
     **/
    @Operation(summary = "批量上传房源资产")
    @PutMapping("/importRoomEquipment")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true)
    })
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:import')")
    public CommonResult<Boolean> importRoomEquipment(@RequestParam("file") MultipartFile file) throws Exception {

        EasyExcel.read(file.getInputStream(), RoomEquipmentImport.class, new RoomEquipmentListener(roomEquipmentService)).sheet().headRowNumber(2).doRead();
        return success(true);
    }

    /**
     * 导出房源资产
     **/
    @GetMapping("/exportRoomEquipment")
    @Operation(summary = "导出房源资产")
    @OperateLog(type = EXPORT)
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:export')")
    public void exportRoomEquipment(@RequestBody RoomEquipmentExportReq roomEquipmentExportReq) {
        // 方法2
        String fileName = "资产" + new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis()) + ".xlsx";

        List<RoomEquipmentExportRespVo> list = roomEquipmentService.exportRoomEquipment(roomEquipmentExportReq);

        //然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(fileName, RoomEquipmentExportRespVo.class).sheet("资产列表").doWrite(list);

    }

    /**
     * 分页查询房源资产列表
     **/
    @Operation(summary = "分页查询房源资产列表")
    @GetMapping("/pageRoomEquipmentByRoomId")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:query')")
    public CommonResult<PageResult<RoomEquipmentPageResp>> pageRoomEquipmentByRoomId(RoomEquipmentPageReqVO reqVO) {

        IPage<RoomEquipmentPageResp> result = roomEquipmentService.pageRoomEquipmentByRoomId(reqVO);
        List<RoomEquipmentPageResp> collect = result.getRecords().stream().peek(e -> e.setPositionTypeName(EquipmentPositionType.getNameByCode(e.getPositionType())))
                .collect(Collectors.toList());
        PageResult<RoomEquipmentPageResp> pageResult = new PageResult<>(collect, result.getTotal());
        return success(pageResult);
    }

    /**
     * 查询资产详情，根据资产ID
     **/
    @Operation(summary = "查询资产详情，根据资产ID")
    @Parameters({
            @Parameter(name = "id", description = "物资ID", required = true, example = "23,123")
    })
    @GetMapping("/queryRoomEquipmentById")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:query')")
    public CommonResult<RoomEquipmentQueryResp> queryRoomEquipmentById(Integer id) {
        RoomEquipmentQueryResp resp = roomEquipmentService.queryRoomEquipmentById(id);
        return success(resp);
    }

    /**
     * 删除房源资产
     **/
    @Operation(summary = "删除房源资产")
    @DeleteMapping("/deleteById")
    @Parameter(name = "id", description = "房源资产ID")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:delete')")
    public CommonResult<Boolean> deleteById(@RequestParam("id") Long id) {
        roomEquipmentService.deleteById(id);
        return success(true);
    }

    @PostMapping("/unbinding-equipment")
    @Parameter(name = "roomId", description = "房源ID")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:equipment:unbinding')")
    public CommonResult<Boolean> unbindingEquipment(@RequestParam("roomId") Long roomId) {
        return success(roomEquipmentService.unbindingEquipment(roomId));
    }

    @Operation(summary = "资产-导入")
    @PostMapping("/equipment-import")
   // @PermitAll
    public CommonResult<String> equipmentImport(@RequestBody EquipmentImportReq req) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        Long userId = SecurityFrameworkUtils.getLoginUser().getId();
//        Long tenantId = 2L;
//        Long userId = 2L;
        req.setTenantId(tenantId);
        req.setUserId(userId);
        String key = "room:equipment:" + codeUtil.nextCode("IM");
        EquipmentImportResult equipmentImportResult = new EquipmentImportResult(1, "导入中");
        stringRedisTemplate.opsForValue().set(key, JsonUtils.toJsonString(equipmentImportResult), 1, TimeUnit.HOURS);
        roomEquipmentService.equipmentImport(req, key);
        return CommonResult.success(key);
    }


    @Operation(summary = "查询资产导入的状态")
    @GetMapping("/get-import-status/{code}")
   // @PermitAll
    @Parameter(name = "key", description = "key")
    public CommonResult<EquipmentImportResult> getImportStatus(@PathVariable("code") String key) {
        String value = stringRedisTemplate.opsForValue().get(key);
        EquipmentImportResult result = JsonUtils.parseObject(value, EquipmentImportResult.class);
        return CommonResult.success(result);
    }
}
